package com.d3works.apps.base.web;

import com.d3works.apps.base.db.PriceList;
import com.d3works.apps.base.db.repo.PriceListRepository;
import com.d3works.apps.base.service.PriceListService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;

@Singleton
public class PriceListController {

  public void historizePriceList(ActionRequest request, ActionResponse response) {
    PriceList priceList = request.getContext().asType(PriceList.class);
    priceList = Beans.get(PriceListRepository.class).find(priceList.getId());
    priceList = Beans.get(PriceListService.class).historizePriceList(priceList);
    response.setReload(true);
  }

  public void checkPriceListLineList(ActionRequest request, ActionResponse response) {
    PriceList priceList = request.getContext().asType(PriceList.class);
    if (priceList.getPriceListLineList() != null
        && priceList.getPriceListLineList().stream().anyMatch(o -> o.getAnomalySelect() > 0)) {
      response.setAlert(
          I18n.get(
              "Warning, the price list contains at least one product that is not renewed or not available for sale."));
    }
  }

  public void checkDates(ActionRequest request, ActionResponse response) {
    PriceList priceList = request.getContext().asType(PriceList.class);
    try {
      Beans.get(PriceListService.class).checkDates(priceList);
    } catch (Exception e) {
      response.setError(e.getMessage());
    }
  }
}
